import { Injectable } from "@nestjs/common";
import axios from "axios";
import * as cheerio from "cheerio";
import xlsx from "node-xlsx";
import * as fs from "fs";

@Injectable()
export class FetchData {
  async getData(keyWords: string) {
    const url = `http://quotes.money.163.com/f10/zycwzb_600519.html#01c01`;
    const { data } = await axios.get(url);
    const $ = cheerio.load(data, { decodeEntities: false });
    let KPINames = $(".col_l .limit_sale > tbody > tr").text().split("\n");
    let keyWordsIndex = (await this.getKeyWordsIndex(KPINames, keyWords)) + 1;

    let title = $(".col_r .scr_table > tbody > .dbrow th").html();
    let titleArr = await this.getTitleContent(title);
    // console.log(titleArr);

    let _data = $(".col_r .scr_table")
      .find("tr")
      .eq(keyWordsIndex)
      .children("td");

    let dataArr = [];
    for (let i = 0; i < _data.length; i++) {
      let temp = _data[i];
      dataArr.push($(temp).text().trim());
    }
    await this.buildXlsx(titleArr, dataArr);
    // await this.buildXlsx({
    //   titleArr,
    //   dataArr,
    // });
    // console.log(dataArr);

    // let s = title.match(/([\S\s]*?)/g);
    // let reg = new RegExp(/<th width="117">([\S\s]*?)<\/th>/gi);
    // title = title.replace(reg, RegExp.$2);
    // console.log(title);
    // console.log(title);
    // let table_title = $(".col_r .scr_table > tbody > .dbrow th");
    // console.log(Object.keys(table_title));
    // console.log(table_title[0].childNodes);
    // let res = util.inspect(table_title[0].children[0]);
    // let list = new Array();
    // for (let i = 0; i < table_title.length; i++) {
    //   list[i] = util.inspect(table_title[i].children[0]);
    // }
    // console.log(list);
    // let matches = table_title.match(/<th>([^<]*)<\/th>/);
    // console.log(matches);
    // return _data;
  }

  // 获取关键词的在table中是第几行
  async getKeyWordsIndex(arr: string[], keyWord: string) {
    let current: string[] = [];
    current = arr.map((item) => item.trim()).filter((item) => item !== "");
    let keyWordsIndex = current.indexOf(`${keyWord}`);
    return keyWordsIndex;
  }

  async getTitleContent(title: string) {
    let titleArr = [];
    let index = 0;
    for (let i = 0; i < title.length / 10; i++) {
      titleArr[i] = title.substring(index, index + 10);
      index += 10;
    }
    return titleArr;
  }

  async buildXlsx(titleArr, dataArr) {
    const excelBuffer = xlsx.build([
      { name: "sheet1", data: [titleArr, dataArr] },
    ]);
    fs.writeFileSync("data.xlsx", excelBuffer, "buffer");
    console.log("导出 excel 成功");
  }

  async cheerioTest() {
    let url = `<ul id = "fruits">...</ul>`;
    let $ = cheerio.load(url);
    console.log("$:", $.length);
    let data = $("#fruits").text();
    console.log("data: ", data);
    return data;
  }
}
